import {
  setToken,
  setRefreshToken,
  removeToken,
  removeRefreshToken,
} from "@/util/auth";
import { Message } from "element-ui";
import { setStore, getStore } from "@/util/store";
import { isURL, validatenull } from "@/util/validate";
import { deepClone } from "@/util/util";
import website from "@/config/website";

import {
  registeredNewUser, //
  login, //
  loginBySocial,
  loginBySso,
  getUserInfo,
  logout,
  refreshToken,
  getButtons,
} from "@/api/user";
import { getTopMenu, getRoutes, getPermissionTree } from "@/api/system/menu";
import md5 from "js-md5";
import staticRouting from "@/util/staticRouting";
let accountPathList = [];
function getAccountPath(arr) {
  arr.forEach((line) => {
    accountPathList.push(line.Path);
    if (line.Child && line.Child.length) {
      getAccountPath(line.Child);
    }
  });
  return accountPathList;
}

function addPath(ele, first) {
  const menu = website.menu;
  const propsConfig = menu.props;
  const propsDefault = {
    label: propsConfig.label || "name",
    path: propsConfig.path || "path",
    icon: propsConfig.icon || "icon",
    children: propsConfig.children || "children",
  };
  const icon = ele[propsDefault.icon];
  ele[propsDefault.icon] = validatenull(icon) ? menu.iconDefault : icon;
  const isChild =
    ele[propsDefault.children] && ele[propsDefault.children].length !== 0;
  // console.log(ele, "routers====================");

  // 添加权限
  if (ele.type == 2) {
    const curPermission = getStore({ name: "permission" });
    const key = ele.route.split("/")[ele.route.split("/").length - 1];
    const trPer = { ...curPermission };
    trPer[key] = true;
    setStore({ name: "permission", content: trPer });
  }

  if (!isChild) {
    ele[propsDefault.children] = [];
  }
  if (!isChild && first && !isURL(ele[propsDefault.path])) {
    ele[propsDefault.path] = ele[propsDefault.path] + "/index";
    return ele;
  } else {
    ele[propsDefault.children] = ele[propsDefault.children]
      .map((child) => {
        return addPath(child);
      })
      .filter((item) => item.type != 2);

    return ele;
  }
}

const computedAsyncRoutes = (asyncRoutes, routes) => {
  //过滤出当前用户【超级管理|普通员工】需要展示的异步路由
  return asyncRoutes.filter((item) => {
    //递归:别忘记还有2、3、4、5、6级路由
    if (item.children && item.children.length) {
      item.children = computedAsyncRoutes(item.children, routes);
    }

    //数组当中没有这个元素返回索引值-1，如果有这个元素返回的索引值一定不是-1
    if (routes.includes(item.route)) {
      return true;
    } else if (item.children && item.children.length) {
      return true;
    } else {
      return false;
    }
  });
};

const user = {
  state: {
    registerUserReturnInfo:
      getStore({ name: "registerUserReturnInfo" }) || null, // 注册用户返回信息
    tenantId: getStore({ name: "tenantId" }) || "",
    userInfo: getStore({ name: "userInfo" }) || [],
    permission: getStore({ name: "permission" }) || {},
    roles: [],
    menuId: {},
    menu: getStore({ name: "menu" }) || [],
    menuAll: getStore({ name: "menuAll" }) || [],
    token: getStore({ name: "token" }) || "",
    refreshToken: getStore({ name: "refreshToken" }) || "",
    userType: getStore({ name: "userType" }) || "admin", // 用户类型：admin或agent
  },
  actions: {
    //注册新用户
    registerNewUser({ commit }, params) {
      return new Promise((resolve, reject) => {
        registeredNewUser(params)
          .then((res) => {
            const resData = res.data.data;
            commit("SET_REGISTER_INFO", resData);
            resolve();
          })
          .catch((error) => {
            reject(error);
          });
      });
    },
    //登录
    LoginByUsername({ commit }, userInfo) {
      return new Promise((resolve, reject) => {
        login(userInfo)
          .then((res) => {
            const resData = res.data;
            console.log("登录:1111111111111111111111", resData);

            commit("SET_TOKEN", resData.token);
            commit("SET_USER_INFO", resData.user);
            commit("DEL_ALL_TAG");
            commit("CLEAR_LOCK");

            // 保存用户类型信息（根据permissions判断）
            const isAgent = resData.permissions && resData.permissions.length > 0;
            commit("SET_USER_TYPE", isAgent ? "agent" : "admin");

            // localStorage.setItem(website.key + "-routes", resData.menu);
            localStorage.setItem(
              website.key + "-user",
              JSON.stringify(resData.user)
            );

            resolve(resData);
          })
          .catch((error) => {
            reject(error);
          });
      });
    },
    //获取用户信息
    GetUserInfo({ commit }) {
      return new Promise((resolve, reject) => {
        getUserInfo()
          .then((res) => {
            const data = res.data.data;
            commit("SET_ROLES", data.roles);
            resolve(data);
          })
          .catch((err) => {
            reject(err);
          });
      });
    },
    //刷新token
    refreshToken({ state, commit }, userInfo) {
      window.console.log("handle refresh token");
      return;
    },
    // 登出
    LogOut({ commit }) {
      return new Promise((resolve, reject) => {
        // logout()
        //   .then(() => {
        commit("SET_TOKEN", "");
        commit("SET_MENU", []);
        commit("SET_MENU_ALL_NULL", []);
        commit("SET_ROLES", []);
        commit("SET_TAG_LIST", []);
        commit("DEL_ALL_TAG");
        commit("CLEAR_LOCK");
        commit("SET_USER_TYPE", "admin"); // 重置用户类型
        removeToken();
        removeRefreshToken();
        resolve();
        // })
        // .catch((error) => {
        //   reject(error);
        // });
      });
    },
    //注销session
    FedLogOut({ commit }) {
      return new Promise((resolve) => {
        commit("SET_TOKEN", "");
        commit("SET_MENU_ALL_NULL", []);
        commit("SET_MENU", []);
        commit("SET_ROLES", []);
        commit("SET_TAG_LIST", []);
        commit("DEL_ALL_TAG");
        commit("CLEAR_LOCK");
        commit("SET_USER_TYPE", "admin"); // 重置用户类型
        removeToken();
        removeRefreshToken();
        resolve();
      });
    },
    //获取顶部菜单
    GetTopMenu() {
      return new Promise((resolve) => {
        getTopMenu().then((res) => {
          const data = res.data.data || [];
          resolve(data);
        });
      });
    },
    //获取系统菜单
    GetMenu({ commit, dispatch, state }, topMenuId) {
      return new Promise((resolve) => {
        // getPermissionTree().then((res) => {
        let menuData = ''
        // admin 管理员
        const data = [
          {
            ID: "01JPHKWCFNG9S8TW19T3DQJSE9",
            Name: "数据统计",
            Path: "/home",
            Child: [
              {
                ID: "01JPHM19C61FE94B7NZS4SA4Z3",
                Name: "数据统计",
                Path: "/home/dataStatistics",
                ParentID: "01JPHKWCFNG9S8TW19T3DQJSE9",
                Child: null,
              },
            ],
          },
          {
            ID: "01JPHKWCFNG9S8TW19T3DQJSE9",
            Name: "代理商管理",
            Path: "/agentManagement",
            Child: [
              {
                ID: "01JPHM19C61FE94B7NZS4SA4Z3",
                Name: "代理商列表",
                Path: "/agentManagement/list",
                ParentID: "01JPHKWCFNG9S8TW19T3DQJSE9",
                Child: null,
              },
            ],
          },
          {
            ID: "01JPHKWCFNG9S8TW19T3DQJSE9",
            Name: "用户管理",
            Path: "/userManagement",
            Child: [
              {
                ID: "01JPHM19C61FE94B7NZS4SA4Z3",
                Name: "用户列表",
                Path: "/userManagement/list",
                ParentID: "01JPHKWCFNG9S8TW19T3DQJSE9",
                Child: null,
              },
            ],
          },
          {
            ID: "01JPHKWCFNG9S8TW19T3DQJSE9",
            Name: "车主认证",
            Path: "/carOwner",
            Child: [
              {
                ID: "01JPHM19C61FE94B7NZS4SA4Z3",
                Name: "车主认证列表",
                Path: "/carOwner/list",
                ParentID: "01JPHKWCFNG9S8TW19T3DQJSE9",
                Child: null,
              },
            ],
          },
          {
            ID: "01JPHKWCFNG9S8TW19T3DQJSE9",
            Name: "行程管理",
            Path: "/itineraryManagement",
            Child: [
              {
                ID: "01JPHM19C61FE94B7NZS4SA4Z3",
                Name: "行程列表",
                Path: "/itineraryManagement/list",
                ParentID: "01JPHKWCFNG9S8TW19T3DQJSE9",
                Child: null,
              },
            ],
          },
          {
            ID: "01JPHKWCFNG9S8TW19T3DQJSE9",
            Name: "优惠券包管理",
            Path: "/coupon",
            Child: [
              {
                ID: "01JPHM19C61FE94B7NZS4SA4Z3",
                Name: "优惠券列表",
                Path: "/coupon/list",
                ParentID: "01JPHKWCFNG9S8TW19T3DQJSE9",
                Child: null,
              },
              {
                ID: "01JPHM19C61FE94B7NZS4SA4Z3",
                Name: "车主优惠券列表",
                Path: "/coupon/ownerCouponList",
                ParentID: "01JPHKWCFNG9S8TW19T3DQJSE9",
                Child: null,
              },
              {
                ID: "01JPHM19C61FE94B7NZS4SA4Z5",
                Name: "优惠券详情",
                Path: "/coupon/detail",
                ParentID: "01JPHKWCFNG9S8TW19T3DQJSE9",
                Child: null,
              },
            ],
          },
          {
            ID: "01JPHKWCFNG9S8TW19T3DQJSE9",
            Name: "投诉管理",
            Path: "/complaint",
            Child: [
              {
                ID: "01JPHM19C61FE94B7NZS4SA4Z3",
                Name: "投诉管理列表",
                Path: "/complaint/comList",
                ParentID: "01JPHKWCFNG9S8TW19T3DQJSE9",
                Child: null,
              },
            ],
          },
           {
            ID: "01JPHKWCFNG9S8TW19T3DQJSE9",
            Name: "咨询管理",
            Path: "/consultation",
            Child: [
              {
                ID: "01JPHM19C61FE94B7NZS4SA4Z3",
                Name: "咨询管理列表",
                Path: "/consultation/conList",
                ParentID: "01JPHKWCFNG9S8TW19T3DQJSE9",
                Child: null,
              },
            ],
          },
          {
            ID: "01JPHKWCFNG9S8TW19T3DQJSE9",
            Name: "线路管理",
            Path: "/pathMannage",
            Child: [
              {
                ID: "01JPHM19C61FE94B7NZS4SA4Z3",
                Name: "线路列表",
                Path: "/pathMannage/list",
                ParentID: "01JPHKWCFNG9S8TW19T3DQJSE9",
                Child: null,
              },
            ],
          },
          {
            ID: "01JPHKWCFNG9S8TW19T3DQJSE9",
            Name: "banner管理",
            Path: "/banners",
            Child: [
              {
                ID: "01JPHM19C61FE94B7NZS4SA4Z3",
                Name: "banner管理列表",
                Path: "/banners/bannerList",
                ParentID: "01JPHKWCFNG9S8TW19T3DQJSE9",
                Child: null,
              },
            ],
          },
          {
            ID: "01JPHKWCFNG9S8TW19T3DQJSE9",
            Name:'报警中心',
            Path:'/alarmCenter',
            Child:[
              {
                ID:'01JPHM19C61FE94B7NZS4SA4Z3',
                Name:'报警中心列表',
                Path:'/alarmCenter/alarmList',
                ParentID:'01JPHKWCFNG9S8TW19T3DQJSE9',
                Child:null
              }
            ]
          },
          {
            ID: "01JPHKWCFNG9S8TW19T3DQJSE9",
            Name: "系统配置中心",
            Path: "/systemConfigCenter",
            Child: [
              {
                ID: "01JPHM19C61FE94B7NZS4SA4Z3",
                Name: "系统配置",
                Path: "/systemConfigCenter/config",
                ParentID: "01JPHKWCFNG9S8TW19T3DQJSE9",
                Child: null,
              },
            ],
          },
        ];
        // agent 代理商
        const agentData = [
           {
            ID: "01JPHKWCFNG9S8TW19T3DQJSE9",
            Name: "数据统计",
            Path: "/home",
            Child: [
              {
                ID: "01JPHM19C61FE94B7NZS4SA4Z3",
                Name: "数据统计",
                Path: "/home/dataStatistics",
                ParentID: "01JPHKWCFNG9S8TW19T3DQJSE9",
                Child: null,
              },
            ],
          },
        ];

        // 根据用户类型选择菜单数据
        if (state.userType === "agent") {
          menuData = agentData;
        } else {
          menuData = data;
        }

        let allPath = getAccountPath(menuData);
        localStorage.setItem(website.key + "-routes", allPath);
        let menu = computedAsyncRoutes(staticRouting, allPath); //allPath);
        menu = menu.map((ele) => {
          return addPath(ele, true);
        });
        // console.log(menu, "this is menu-------------");
        commit("SET_MENU_ALL", menu);
        commit("SET_MENU", menu);
        resolve(menu);
        // });
      });
    },
    //获取系统按钮
    GetButtons({ commit }) {
      return new Promise((resolve) => {
        getButtons().then((res) => {
          const data = res.data.data;
          commit("SET_PERMISSION", data);
          resolve();
        });
      });
    },
  },
  mutations: {
    SET_REGISTER_INFO: (state, result) => {
      console.log("SET_REGISTER_INFO：", result);
      state.registerUserReturnInfo = result;
      setStore({
        name: "registerUserInfo",
        content: state.registerUserReturnInfo,
      });
    },
    SET_TOKEN: (state, token) => {
      // console.log(120, token);

      setToken(token);
      state.token = token;
      setStore({ name: "token", content: state.token });
    },
    SET_MENU_ID(state, menuId) {
      state.menuId = menuId;
    },
    SET_MENU_ALL: (state, menuAll) => {
      // let menu = state.menuAll;
      // menuAll.forEach((ele) => {
      //   if (
      //     !menu.find(
      //       (item) => item.label === ele.label && item.path === ele.path
      //     )
      //   ) {
      //     menu.push(ele);
      //   }
      // });
      state.menuAll = menuAll;
      setStore({ name: "menuAll", content: state.menuAll });
    },
    SET_MENU_ALL_NULL: (state) => {
      state.menuAll = [];
      setStore({ name: "menuAll", content: state.menuAll });
    },
    SET_MENU: (state, menu) => {
      state.menu = menu;
      setStore({ name: "menu", content: state.menu });
    },
    SET_REFRESH_TOKEN: (state, refreshToken) => {
      setRefreshToken(refreshToken);
      state.refreshToken = refreshToken;
      setStore({ name: "refreshToken", content: state.refreshToken });
    },
    SET_TENANT_ID: (state, tenantId) => {
      state.tenantId = tenantId;
      setStore({ name: "tenantId", content: state.tenantId });
    },
    SET_USER_INFO: (state, userInfo) => {
      if (validatenull(userInfo.avatar)) {
        userInfo.avatar = "/img/bg/test2.jpg";
      }
      state.userInfo = userInfo;
      setStore({ name: "userInfo", content: state.userInfo });
    },
    SET_ROLES: (state, roles) => {
      state.roles = roles;
    },
    SET_PERMISSION: (state, permission) => {
      let result = [];

      function getCode(list) {
        list.forEach((ele) => {
          if (typeof ele === "object") {
            const chiildren = ele.children;
            const code = ele.code;
            if (chiildren) {
              getCode(chiildren);
            } else {
              result.push(code);
            }
          }
        });
      }

      getCode(permission);
      state.permission = {};
      result.forEach((ele) => {
        state.permission[ele] = true;
      });
      setStore({ name: "permission", content: state.permission });
    },
    SET_USER_TYPE: (state, userType) => {
      state.userType = userType;
      setStore({ name: "userType", content: state.userType });
    },
  },
};
export default user;
